package org.groupg.practice.guiPractice.mycomponent;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;

public class DownloadWithSpeedMonitor extends JFrame {
    private JProgressBar progressBar;
    private JLabel speedLabel;
    private JLabel fileSizeLabel;
    private JLabel statusLabel;
    private JButton downloadButton;
    private JTextField urlTextField;
    private JTextField savePathTextField;
    private volatile boolean downloading = false;
    private long startTime = 0;

    // 用于格式化速度显示
    private DecimalFormat speedFormat = new DecimalFormat("0.00");

    public DownloadWithSpeedMonitor() {
        setTitle("Java 下载速度监视器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 200);
        setLocationRelativeTo(null);

        // 创建UI组件
        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        speedLabel = new JLabel("速度: 0 KB/s");
        fileSizeLabel = new JLabel("文件大小：x KB");
        statusLabel = new JLabel("准备就绪");
        downloadButton = new JButton("开始下载");
        urlTextField = new JTextField("https://modelscope.cn/models/deepseek-ai/DeepSeek-V3.2-Exp/resolve/master/model-00001-of-000163.safetensors", 30);
        savePathTextField = new JTextField("F:\\新建文件夹\\file.zip", 30);

        // 布局
        setLayout(new BorderLayout());

        JPanel topPanel = new JPanel(new GridLayout(4, 1, 5, 5));
        topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JPanel urlPanel = new JPanel(new BorderLayout());
        urlPanel.add(new JLabel("下载URL:"), BorderLayout.WEST);
        urlPanel.add(urlTextField, BorderLayout.CENTER);

        JPanel pathPanel = new JPanel(new BorderLayout());
        pathPanel.add(new JLabel("保存路径:"), BorderLayout.WEST);
        pathPanel.add(savePathTextField, BorderLayout.CENTER);

        topPanel.add(urlPanel);
        topPanel.add(pathPanel);
        topPanel.add(statusLabel);
        topPanel.add(fileSizeLabel);
        topPanel.add(speedLabel);


        add(topPanel, BorderLayout.NORTH);
        add(progressBar, BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel();
        bottomPanel.add(downloadButton);
        add(bottomPanel, BorderLayout.SOUTH);

        // 下载按钮事件
        downloadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!downloading) {
                    startDownload();
                } else {
                    stopDownload();
                }
            }
        });
    }

    private void startDownload() {
        String fileUrl = urlTextField.getText();
        String savePath = savePathTextField.getText();

        if (fileUrl.isEmpty() || savePath.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入下载URL和保存路径");
            return;
        }

        downloading = true;
        downloadButton.setText("取消下载");
        statusLabel.setText("连接中...");
        speedLabel.setText("速度: 计算中...");
        progressBar.setValue(0);

        // 在后台线程执行下载，避免界面卡顿:cite[2]
        new DownloadThread(fileUrl, savePath).start();
    }

    private void stopDownload() {
        downloading = false;
        downloadButton.setText("开始下载");
        statusLabel.setText("下载已取消");
    }

    // 实时更新速度显示:cite[6]
    private void updateSpeed(final long bytesRead, final long timeElapsed, final long filesize) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (timeElapsed > 0) {
                    double bytesPerMillisecond = (double) bytesRead / timeElapsed;
                    double kbps = bytesPerMillisecond * 1000 / 1024; // 转换为KB/s
                    double mbps = kbps / 1024; // 转换为MB/s

                    if (mbps >= 1) {
                        speedLabel.setText("速度: " + speedFormat.format(mbps) + " MB/s");
                    } else {
                        speedLabel.setText("速度: " + speedFormat.format(kbps) + " KB/s");
                    }
                }

                // 更新进度条:cite[6]
                int progress = 0;
                if (bytesRead > 0) {
                    if (filesize > 0) {
                        progress = (int) (bytesRead / filesize) * 100; // 假设每MB增加1%进度
                        if (bytesRead == filesize) progress = 100;
                        progressBar.setValue(progress);
                    }else {

                    }
                    // 注意: 实际应用中需要知道文件总大小来准确计算进度
                    // 这里只是示例，实际进度应在知道文件总大小后计算

                }

            }
        });
    }

    // 下载线程类
    private class DownloadThread extends Thread {
        private String fileUrl;
        private String savePath;

        public DownloadThread(String fileUrl, String savePath) {
            this.fileUrl = fileUrl;
            this.savePath = savePath;
        }

        @Override
        public void run() {
            InputStream inputStream = null;
            FileOutputStream outputStream = null;

            try {
                URL url = new URL(fileUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                // 获取文件大小用于进度显示（如果服务器提供）
                int fileSize = connection.getContentLength();

                if (fileSize != -1) {
                    double fileMB = fileSize / (1024.0 * 1024.0);
                    fileSizeLabel.setText("文件大小: " +
                            speedFormat.format(fileMB) + " MB");
                    progressBar.setIndeterminate(false);
                    progressBar.setStringPainted(true);
                } else {
                    fileSizeLabel.setText("文件大小: 未知");
                    progressBar.setIndeterminate(true);
                    progressBar.setStringPainted(false);
                }

                inputStream = connection.getInputStream();
                outputStream = new FileOutputStream(savePath);

                byte[] buffer = new byte[8192]; // 8KB缓冲区:cite[9]
                int bytesRead;
                long totalBytesRead = 0;

                startTime = System.currentTimeMillis();
                long lastUpdateTime = startTime;
                long lastBytesRead = 0;

                statusLabel.setText("下载中...");

                while (downloading && (bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;

                    long currentTime = System.currentTimeMillis();
                    long elapsedTime = currentTime - startTime;

                    // 每500毫秒更新一次速度显示，避免过于频繁的UI更新:cite[6]
                    if (currentTime - lastUpdateTime >= 500) {
                        updateSpeed(totalBytesRead, elapsedTime, fileSize);
                        lastUpdateTime = currentTime;

                        // 更新状态信息
                        long finalTotalBytesRead = totalBytesRead;
                        SwingUtilities.invokeLater(() -> {
                            statusLabel.setText("已下载: " +
                                    String.format("%.2f", finalTotalBytesRead / (1024.0 * 1024.0)) + " MB");
                        });
                    }
                }

                if (downloading) {
                    // 下载完成
                    long endTime = System.currentTimeMillis();
                    long totalTime = endTime - startTime;

                    long finalTotalBytesRead1 = totalBytesRead;
                    SwingUtilities.invokeLater(() -> {
                        statusLabel.setText("下载完成");
                        double totalMB = finalTotalBytesRead1 / (1024.0 * 1024.0);
                        double totalSeconds = totalTime / 1000.0;
                        double averageSpeed = totalMB / totalSeconds;

                        speedLabel.setText("平均速度: " +
                                speedFormat.format(averageSpeed) + " MB/s");
                        progressBar.setValue(100);

                        JOptionPane.showMessageDialog(DownloadWithSpeedMonitor.this,
                                String.format("下载完成!\\n文件大小: %.2f MB\\n总时间: %.1f 秒\\n平均速度: %.2f MB/s",
                                        totalMB, totalSeconds, averageSpeed));
                    });
                }

            } catch (Exception e) {
                if (downloading) {
                    SwingUtilities.invokeLater(() -> {
                        statusLabel.setText("下载错误: " + e.getMessage());
                        speedLabel.setText("速度: 错误");
                    });
                    e.printStackTrace();
                }
            } finally {
                downloading = false;

                SwingUtilities.invokeLater(() -> {
                    downloadButton.setText("开始下载");
                });

                try {
                    if (inputStream != null) inputStream.close();
                    if (outputStream != null) outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        // 设置UI风格
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(() -> {
            new DownloadWithSpeedMonitor().setVisible(true);
        });
    }
}